package br.nextfm.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.nextfm.dao.AlbumDao;
import br.nextfm.dao.ArtistaDao;
import br.nextfm.model.Album;
import br.nextfm.model.Artista;

public class AtualizaAlbum extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		int id = Integer.parseInt(request.getParameter("id"));
		
		AlbumDao dao = new AlbumDao();
		Album album = dao.get(id);
		ArtistaDao artistaDao = new ArtistaDao();
		
		request.setAttribute("albumSelecionado", album);
		request.setAttribute("editar", true);
		request.setAttribute("albums", dao.getAll());
		request.setAttribute("artistas", artistaDao.getAll());
		request.getRequestDispatcher("album.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String nome = request.getParameter("nome");
		String descricao = request.getParameter("descricao");
		String tags = request.getParameter("tags");
		String imagem = request.getParameter("foto");
		
		int idArtista = Integer.parseInt(request.getParameter("artista"));
		int ano = Integer.parseInt(request.getParameter("ano"));
		int id = Integer.parseInt(request.getParameter("id"));
		
		AlbumDao dao = new AlbumDao();
		ArtistaDao artistaDao = new ArtistaDao();
		
		Album album = dao.get(id);
		Artista artista = artistaDao.get(idArtista);
		
		album.setAno(ano);
		album.setArtista(artista);
		album.setDescricao(descricao);
		album.setImagem(imagem);
		album.setNome(nome);
		album.setTags(tags);
		album.setArtista(artista);
		
		if (!artista.getAlbuns().contains(album))
			artista.getAlbuns().add(album);
		
		if (dao.update(album)) {
			artistaDao.update(artista);
			
		}
		
		request.setAttribute("albums", dao.getAll());
		request.setAttribute("artistas", artistaDao.getAll());
		request.getRequestDispatcher("album.jsp").forward(request, response);
		
	}

}
